import re
from flask import Blueprint,request,jsonify
import json
from db import db1
from utils.comm import send_message
from rediscon import r
from utils.jwtc import myjwt
bp_auser = Blueprint('adminuser',__name__)

@bp_auser.route('/roleM',methods=['POST','GET'])
def roleM():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "select id from roles where name='%s'"%(data['name'])
        res = db1.find(sql)
        if res:
            return jsonify({'code':10011,})
        else:
            sqlq = "insert into roles values(0,'%s')"%(data['name'])
            db1.update(sqlq)
            return jsonify({'code':200})
    else:
        sql = "select * from roles"
        res = db1.findall(sql)
        return({'code':200,'list':res})


@bp_auser.route('/resourcesM',methods=['POST','GET'])
def resourcesM():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "select id from resources where name='%s'"%(data['name'])
        res = db1.find(sql)
        if res:
            return jsonify({'code':10011})
        else:
            sql = "insert into resources values(0,'%s','%s')"%(data['name'],data['url'])
            db1.update(sql)
            return jsonify({'code':200})
    else:
        role_id = request.args.get('id')
        if role_id:
            sql = "select * from roles_resource where role_id=%d"%(int(role_id))
            res = db1.findall(sql)
            list = []
            for i in res:
                list.append(i['resource_id'])
        else:
            
            sql = "select * from resources"
            list = db1.findall(sql)
        return jsonify({'code':200,'list':list})


@bp_auser.route('/users',methods=['POST'])
def users():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    sql = "insert into admin_user values(0,'%s','%s',%d,%d)"%(data['name'],data['password'],0,int(data['role_id']))
    db1.update(sql)
    return jsonify({'code':200})


@bp_auser.route('/setresources',methods=['POST'])
def setresources():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    #删除此roleid对应的所有资源
    sql = "delete from roles_resource where role_id=%d"%(int(data['role_id']))
    db1.update(sql)
    ids = data['ids']
    for i in ids:
        sql1 = "insert into roles_resource values(%d,%d)"%(int(data['role_id']),i)
    db1.update(sql1)
    return jsonify({'code':200})



import random
import re
@bp_auser.route('/sendsms')
def sendsms():
    # 获取手机号
    mobile = request.args.get('mobile')
    res = re.match('^1[3-9]\d{9}$',mobile)
    if res:
        pass
    else:
        return jsonify({'code':20010})

    # 随机生成验证码
    code = random.randint(100000,999999)
    # 调用短信接口
    flag = send_message(mobile,code,1)
    if flag:
        r.set_str(mobile,code,60)
    else:
        pass
    return jsonify({'code':200})



@bp_auser.route('/login',methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    print(data)
    value = r.get_str(data['mobile'])
    if not value:
        return jsonify({'code':20022,'mes':'验证码不存在·'})
        # redis取出来的验证码跟输入的进行对比
    if int(value)==int(data['code']):
        sql = "select * from admin_user where name='%s'"%(data['mobile'])
        res = db1.find(sql)
        if res:
            r.del_str(data['mobile'])
            token = myjwt.jwt_encode(data)
            newtoken = myjwt.jwt_decode(token)
            print(token)
            print(newtoken)
            sql = "select * from resources inner join roles_resource on resources.id=resource_id where role_id=%d"%(int(res['role_id']))
            print(sql)
            reslist = db1.findall(sql)
            return jsonify({'code':200,'user':res,'token':token,'newtoken':newtoken,'list':reslist})
        else:
            return jsonify({'code':20032,'mes':'用户不存在'})
    else:
            return jsonify({'code':20010,'mes':'验证码输入错误'})        
    

